package reflectdemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author : zzr
 * @description :
 * @date :
 */
public class ReflectDemo {

    //通过反射来 实例化一个对象
    public static void reflectNewInstance() {
        Class<?> c1;
        try {
            c1 = Class.forName("reflectdemo.Student");
            Student student = (Student) c1.newInstance();
            System.out.println(student);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    // 反射私有的构造方法
    public static void reflectPrivateConstructor() {
        Class<?> c1;
        try {
            c1 = Class.forName("reflectdemo.Student");

            Constructor<Student> con =
                    (Constructor<Student>) c1.getDeclaredConstructor(String.class, int.class);

            con.setAccessible(true);

            Student student = con.newInstance("zzz", 18);

            System.out.println(student);

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    //反射私有方法
    public static void reflectPrivateMethod() {
        Class<?> c1;
        try {
            c1 = Class.forName("reflectdemo.Student");

            Method method = c1.getDeclaredMethod("function", String.class);

            method.setAccessible(true);

            Student student = (Student)c1.newInstance();

            method.invoke(student,"我是一个参数");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
//        reflectNewInstance();
//        reflectPrivateConstructor();
        reflectPrivateMethod();
    }

}
